<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Common;

class ProductsController extends ApiController
{
    public $redis;
    public $collects;
    public $generalize_goods_ids = '';

    public function initialize()
    {
        parent::initialize();
        $this->redis     = $this->getDI()->getredis();
    }

    /**
     * 达人说说分类
     */
    public function talentcateAction(){
        $data[0]['name']='大家都在看';
        $data[0]['id']=0;
        $data[1]['name']='好看';
        $data[1]['id']=1;
        $data[2]['name']='潮流';
        $data[2]['id']=2;
        $data[3]['name']='美食';
        $data[3]['id']=3;
        $data[4]['name']='生活';
        $data[4]['id']=4;
        $this->ok($data);
    }


    /**
     * @func 发现好物  达人说
     * @talentcat 大家都在逛类目，文章类别（0.全部，1.好物,2.潮流,3.美食,4.生活）
     * @return Mixed
     */
    public function talentAction()
    {
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page'] = 1;
        }
        if(!isset($this->params['talentcat']) || empty($this->params['talentcat'])){
            $this->params['talentcat'] = 0;
        }
        $redis_key="talent_{$this->params['page']}_{$this->params['talentcat']}";
        $res=$this->cache->get_cache($redis_key);
        if(!$res) {
            $res = $this->haodanku->talent($this->params);
            $res = isset($res['data']) ? $res['data'] : [];
            $this->cache->set_cache($redis_key,$res);
        }
        $this->ok($res, 1, 'ok');
    }


    /**
     * @func 文章API（达人说详情）
     * @return Mixed
     */
    public function talentArticleAction()
    {
        if(!isset($this->params['id']) || empty($this->params['id'])){
            $this->fail(-1,'详情id不能为空');
        }
        $redis_key="talentArticle_{$this->params['id']}";
        $res=$this->cache->get_cache($redis_key);
        if(!$res) {
            $haodanku_res = $this->haodanku->talent_article($this->params);
            $res = isset($haodanku_res['data']) ? $haodanku_res['data'] : [];
            if (isset($res['article']) && !empty($res['article'])) {
                $res['article'] = htmlspecialchars_decode($res['article']);
            }
            $this->cache->set_cache($redis_key,$res);
        }
        $this->ok($res);
    }


    /**
     * 母婴专区
     * 母婴_备孕	4040
        母婴_0至6个月	4041
        母婴_4至6岁	4044
        母婴_7至12个月	4042
        母婴_1至3岁	4043
        母婴_7至12岁	4045
     */
    public function motherbabyAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page']=1;
        }
        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size']=10;
        }
        if(!isset($this->params['column_id']) || empty($this->params['column_id'])){
            $this->params['column_id']=4040;
        }
        $data = $this->taobao->TbkDgOptimusMaterialRequest(4040,$this->params['page'],$this->params['page_size']);
        $this->ok($data);
    }


    /**
     * 超级返
     */
//    public function super_fanAction(){
//        if (in_array($params['column_second_id'], [13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376])) {
//            /**
//             * @link https://market.m.taobao.com/app/qn/toutiao-new/index-pc.html?spm=a219t.11816995.1998910419.d1856e3ff.675c75a5BYYRPd#/detail/10628875?_k=vt9nz0
//             * @see taobao::TbkDgOptimusMaterialRequest
//             */
//            $data = $this->taobao->TbkDgOptimusMaterialRequest($params['column_second_id'],$params['page'],$params['page_size']);
//    }



    /**
     * 商品列表()
     * @return mixed
     */
    public function listAction()
    {
        $params = $this->params;
        isset($params['page']) or $params['page'] = 1;
        isset($params['page_size']) or $params['page_size'] = 10;


        $result = [
            'data'      => [],
            'total'     => 0,
            'next_page' => null
        ];

        $generalize = [];
        $is_column  = isset($params['column_id']) && $params['column_id'] && isset($params['column_second_id']) ? true : false;

        $find = $is_column && $params['column_id'] == 2 && in_array($params['column_second_id'], [0, 1, 2, 3, 4]);
        if ($find && empty($params['talent_article_id'])) {//发现好物 0.全部，1.好物,2.潮流,3.美食,4.生活
            $this->fail('-1', 'talent_article_id不能为空');
        }

        if ($params['page'] == 1) {//推广
            if ($is_column) {
                $key = 'Generalize_column_' . $params['column_id'] . '_second_' . $params['column_second_id'];
            } else {
                $key = isset($params['category_second_id']) && $params['category_second_id'] ? 'Generalize_categories_' . $params['category_second_id'] : 'Generalize_categories_' . $params['category_id'];
            }
            $list = $this->redis->get($key);
            if (!empty($list)) {
                $list       = json_decode($list, true);
                $generalize = $this->generalize($list, $params);
            }
            if (!empty($generalize['data'])) {
                $this->ok($generalize['data'], 1, 'ok', $generalize['total'], $result['next_page']);
            }
        }

        //二级栏目
        if ($is_column) {
                $id = intval($params['column_second_id']);
            //发现好物 0.全部，1.好物,2.潮流,3.美食,4.生活
            if ($find) {
                $haodanku['id'] = intval($params['talent_article_id']);
                /**
                 * @link https://www.haodanku.com/api/detail/show/24.html
                 * @see Haodanku::talent_article
                 */
                $res = $this->haodanku->talent_article($haodanku);
                if (!empty($res['data']['items'])) {
                    $result['data'] = $this->money_less($res['data']['items']);
                }
                $this->ok($result['data'], 1, 'ok', count($result['data']), $result['next_page']);
            }

            $key    = 'Goods_column_api_switch_' . $params['column_id'] . '_second_' . $id;
            $switch = $this->redis->get($key);
            if ($switch) {//站内商品
                $res = $this->GoodsList($params, $is_column);
                $res['data'] = !empty($res['data'])?$res['data']:[];

                $this->ok($res['data'], 1, 'ok', $res['total'], $result['next_page']);
            } else {//第三方
                $params['min_id'] = $params['page'];
                $params['back']   = $params['page_size'];
                $data             = $this->columnSecondList($params['column_id'], $params);
                $data['data'] = !empty($data['data'])?$data['data']:[];
                $this->ok($data['data'], 1, 'ok', $data['total'], $data['next_page']);
            }
        }

        //分类
        if ((isset($params['category_id']) && !empty($params['category_id'])) || (isset($params['category_second_id']) && !empty($params['category_second_id']))) {
            $key    = 'Goods_list_api_switch';
            $switch = $this->redis->get($key);
            if ($switch) {//站内商品
                $res = $this->GoodsList($params);
                $this->ok($res['data'], 1, 'ok', $res['total'], $result['next_page']);
            } else {//第三方
                $result = $this->categoryList($params);

                $this->ok($result['data'], 1, 'ok', $result['total'], $result['next_page']);
            }
        }

        $this->ok([], 1, 'ok');
    }


    protected function GoodsList($params, $is_column = false)
    {
        $data = [
            'data'  => [],
            'total' => 0
        ];

        if ($is_column) {
            $key   = 'Goods_List_column_id_' . $params['column_id'] . '_column_second_id_' . $params['column_second_id'] . '_page_' . $params['page'] . '_size_' . $params['page_size'] . '_generalize_' . $this->generalize_goods_ids;
            $total = 'Goods_Count_column_id_' . $params['column_id'] . '_column_second_id_' . $params['column_second_id'] . '_generalize_' . $this->generalize_goods_ids;
        } else {
            $key   = 'Goods_List_category_id_' . $params['category_id'] . '_category_second_id_' . $params['category_second_id'] . '_page_' . $params['page'] . '_size_' . $params['page_size'] . '_generalize_' . $this->generalize_goods_ids;
            $total = 'Goods_Count_category_id_' . $params['category_id'] . '_category_second_id_' . $params['category_second_id'] . '_generalize_' . $this->generalize_goods_ids;
        }
        $count = $this->redis->get($total);
        if (!empty($count)) {
            $data['count'] = $count;
            $data['data']  = json_decode($this->redis->get($key), true);
            return $data;
        }

        if ($this->generalize_goods_ids) {
            $params['generalize'] = $this->generalize_goods_ids;
        }

        $params['page'] = $params['page'] - 1;
        $goods          = (new Goods());
        $data['total']  = $goods->goods_count($params);
        if ($data['total']) {
            $data['data'] = $goods->goods_list($params, true);
            $this->redis->set($key, json_encode($data['data']), 300);
            $this->redis->set($total, $data['total'], 300);
        }
        if (!empty($data['data'])) {
            $data['data'] = $this->money_less($data['data']);
        }


        return $data;
    }

    /**
     * 获取推广商品或者广告
     * @param $list
     * @param $params
     * @return array
     */

    private function generalize($list, $params)
    {
        $res                    = [];
        $goods_ids              = [];
        $advertising_ids        = [];
        $goods_list             = [];
        $goods_advertising_list = [];
        foreach ($list as $v) {
            if ($v['type'] == 1) {
                empty($v['id']) or $goods_ids[] = $v['id'];
            } else {
                empty($v['id']) or $advertising_ids[] = $v['id'];
            }
        }
        if ($goods_ids) {
            $this->generalize_goods_ids = implode(',', $goods_ids);
            $params['generalize']       = $this->generalize_goods_ids;
        }
        $goods                      = (new Goods());
        $tem_goods_list             = $goods->goods_generalize_all(['item_id' => implode(',', $goods_ids)], true);
        $tem_goods_list             = $this->money_less($tem_goods_list);
        $tem_goods_advertising_list = (new GoodsAdvertising())->goods_advertising_generalize_all(['id' => implode(',', $advertising_ids)]);
        foreach ($tem_goods_list as $v) {
            $goods_list[$v['GoodsId']] = $v;
        }
        foreach ($tem_goods_advertising_list as $v) {
//            if (!empty($v['app_data'])) {
//                $v['app_data'] = json_decode($v['app_data'], true);
//            }
            if (is_null($v['app_data'])) {
                $v['app_data'] = '';
            }
            $goods_advertising_list[$v['id']] = $v;
        }
        foreach ($list as $v) {
            if ($v['type'] == 1) {
                $item = isset($goods_list[$v['id']]) ? $goods_list[$v['id']] : [];
            } else {
                $item = isset($goods_advertising_list[$v['id']]) ? $goods_advertising_list[$v['id']] : [];
                if (!empty($item)) {
                    $tmp           = $item;
                    $tmp['data']   = $item['app_data'];
                    $tmp['path']   = $item['app_path'];
                    $tmp['notice'] = null;
                    $tmp['is_new'] = 0;
                    $path          = $item['path'];
                    $name          = $item['name'];
                    unset($tmp['id'], $tmp['app_data'], $tmp['app_path'], $tmp['IsAd'], $tmp['relationId']);
                    $item = [];
                    $item = ['name' => $name, 'path' => $path, 'route' => $tmp, 'IsAd' => 1];
                }
            }
            empty($item) or $res[] = $item;
        }
        $total = $goods->goods_count($params);

        //todo  数据不够时
//        $residue = $params['page_size'] - count($res);
//        if ($residue) {
//            $data['total'] = $goods->goods_count($params);
//            if ($data['total']) {
//                $data['list'] = $goods->goods_list($params, true);
//            }
//        }


        return ['data' => $res, 'total' => $total];
    }

    /**
     * 好裆裤 分类查询商品
     * @param $params
     * @return mixed
     */
    protected function categoryList($params)
    {
        $data = [
            'data'      => [],
            'total'     => 10000,
            'next_page' => ''
        ];
        if (isset($params['category_second_id']) && $params['category_second_id']) {
            $params['keyword'] = $this->getCategoryName($params['category_second_id']) . ' ' . $this->getCategoryName($params['category_id']);
            $params['coupon']  = 1;
            /**
             * @see Haodanku::goods_search
             */
            $res               = $this->haodanku->goods_search($params, true);
            $data['data']      = $this->money_less($res['data']);
            $data['next_page'] = $res['min_id'];
        } else {
            /**
             * @see Haodanku::goods_list
             */
            $res               = $this->haodanku->goods_list($params);
            $data['data']      = $this->money_less($res['data']);
            $data['next_page'] = $res['min_id'];
        }


        return $data;
    }

    /**
     * 获取分类名称
     * @param $id
     * @return string
     */
    protected function getCategoryName($id)
    {
        $key      = 'Category_name_list';
        $category = [];
        $cache    = $this->redis->get($key);
        if (!empty($cache)) {
            $category = json_decode($cache, true);
        } else {
            $data = (new Category())->get_all_name('id as category_id,name');
            if (!empty($data)) {
                foreach ($data as $v) {
                    $category[$v['category_id']] = $v['name'];
                }
                $this->redis->set($key, json_encode($category), 3600 * 24 * 7);
            }
        }

        return isset($category[$id]) ? $category[$id] : '';
    }

    /**
     * 二级栏目查询商品
     * @param $id
     * @param $params
     * @return mixed
     */
    protected function columnSecondList($id, $params)
    {
        $res = [
            'data'      => [],
            'total'     => 0,
            'next_page' => 1
        ];
        switch ($id) {
            case 1: //母婴
                if (in_array($params['column_second_id'], [4040,4041,4042,4043,4044,4045])) {
                    /**
                     * @link https://market.m.taobao.com/app/qn/toutiao-new/index-pc.html?spm=a219t.11816995.1998910419.d1856e3ff.675c75a5BYYRPd#/detail/10628875?_k=vt9nz0
                     * @see taobao::TbkDgOptimusMaterialRequest
                     */
                    $data = $this->taobao->TbkDgOptimusMaterialRequest($params['column_second_id'],$params['page'],$params['page_size']);
                    if(!empty($data)){
                        $params['page'] += 1;
                    }
                    $res  = [
                        'data'      => $data,
                        'total'     => 99999,
                        'next_page' => $params['page']
                    ];
                }
                break;
//            case 2: //发现好物 大家都在看 最近更新
//                $params['id'] = $params['column_second_id'];
//                /**
//                 * @link https://www.haodanku.com/api/detail/show/24.html
//                 * @see Haodanku::talent_article
//                 */
//                $data = $this->haodanku->talent_article($params);
//                $res  = [
//                    'data'      => $data['data']['items'],
//                    'total'     => count($data['data']['items']),
//                    'next_page' => $data['min_id']
//                ];
//                break;
            case 3: //大牌闪购
                $params['brand_ids'] = $params['column_second_id'];
                $params['version']   = 'v1.2.0';
                /**
                 * @link http://www.dataoke.com/pmc/api-d.html?id=17
                 * @see Taoke::getgoodslist
                 */
                $data = $this->taoke->getgoodslist($params);
                $res  = [
                    'data'      => $data['data'],
                    'total'     => count($data['data']),
                    'next_page' => 2
                ];
                break;
            case 4: //限时秒杀
                if (in_array($params['column_second_id'], [16, 17])) {//爆单商品/大家都在买
                    /**
                     * @link https://www.haodanku.com/api/detail/show/1.html
                     * @see Haodanku::hot_sale_list
                     */
                    $params['nav'] = $params['column_second_id'] == 16 ? 2 : 1;
                    $params['cid'] = isset($params['cid']) ? intval($params['cid']) : 0;
                    $data          = $this->haodanku->hot_sale_list($params);
                    $res           = [
                        'data'      => $data['data'],
                        'total'     => 10000,
                        'next_page' => $data['min_id']
                    ];
                } else {//限时秒杀
                    $params['hour_type'] = $params['column_second_id'];
                    /**
                     * @link https://www.haodanku.com/api/detail/show/21.html
                     * @see Haodanku::fastbuy
                     */
                    $data = $this->haodanku->fastbuy($params);
                    $res  = [
                        'data'      => isset($data['data']) ? $data['data'] : [],
                        'total'     => isset($data['data']) ? count($data['data']) : 0,
                        'next_page' => isset($data['min_id']) ? $data['min_id'] : null
                    ];
                }
                break;
            case 5: //母婴
                if (in_array($params['column_second_id'], [13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376])) {
                    /**
                     * @link https://market.m.taobao.com/app/qn/toutiao-new/index-pc.html?spm=a219t.11816995.1998910419.d1856e3ff.675c75a5BYYRPd#/detail/10628875?_k=vt9nz0
                     * @see taobao::TbkDgOptimusMaterialRequest
                     */
                    $data = $this->taobao->TbkDgOptimusMaterialRequest($params['column_second_id'],$params['page'],$params['page_size']);
                    if(!empty($data)){
                        $params['page'] += 1;
                    }
                    $res  = [
                        'data'      => $data,
                        'total'     => 99999,
                        'next_page' => $params['page']
                    ];
                }
                break;
            case 6: //
                //好货
                $params['category_id'] = $params['column_second_id'];
                /**
                 * @link https://www.haodanku.com/api/detail/show/32.html
                 * @see Haodanku::douyin
                 */
                $data = $this->haodanku->douyin($params);
                $res  = [
                    'data'      => $data['data'],
                    'total'     => 10000,
                    'next_page' => $data['min_id']
                ];
                break;
            case 7: //偏远包邮
                $params['category_id'] = $params['column_second_id'];
                /**
                 * @link https://www.haodanku.com/api/detail/show/33.html
                 * @see Haodanku::get_free_shipping_data
                 */
                $data = $this->haodanku->get_free_shipping_data($params);
                $res  = [
                    'data'      => $data['data'],
                    'total'     => 10000,
                    'next_page' => $data['min_id']
                ];
                break;
            case 8: //九块九包邮
//                $params['type'] = $params['column_second_id'];
//                /**
//                 * @see Haodanku::low_price_pinkage_data
//                 */
//                $data = $this->haodanku->low_price_pinkage_data($params['type']);
//                $res  = [
//                    'data'      => $data['data'],
//                    'total'     => 1000,
//                    'next_page' => $data['min_id']
//                ];

                $params['cid'] = $params['column_second_id'];
                /**
                 * @link http://www.dataoke.com/pmc/api-d.html?id=15
                 * @see Taoke::opgoodslist
                 */
                $data = $this->taoke->opgoodslist($params);
                $res  = [
                    'data'      => $data['code'] ? $data['data'] : [],
                    'total'     => $data['code'] ? 1000 : 0,
                    'next_page' => null
                ];
                break;
            case 9: //首页底部栏目
                if ($params['column_second_id'] == 1) { //全部
                    $params['cid']     = 1;
                    /**
                     * @link http://www.dataoke.com/pmc/api-d.html?id=15
                     * @see Taoke::opgoodslist
                     */
                    $data = $this->taoke->opgoodslist($params);
                    $res  = [
                        'data'      => $data['code'] ? $data['data'] : [],
                        'total'     => $data['code'] ? 1000 : 0,
                        'next_page' => null
                    ];
                }
                if ($params['column_second_id'] == 2) {//视频
                    /**
                     * @link https://www.haodanku.com/api/detail/show/1.html
                     * @see Haodanku::video
                     */
                    $data = $this->haodanku->video($params);
                    $res  = [
                        'data'      => $data['data'],
                        'total'     => 10000,
                        'next_page' => $data['min_id']
                    ];
                }
                if (in_array($params['column_second_id'], [3, 4])) { // 便宜好货 /大家都在买
                    $page = intval($params['page']);
                    $size = intval($params['page_size']);
                    if ($page > 0) {
                        $page = ($page - 1) * $size;
                    }
                    $key   = 'Products_column_second_id_' . $params['column_second_id'];
                    $cache = $this->redis->get($key);
                    if (!empty($cache)) {
                        $test = json_decode($cache, true);
                        if (!is_array($test) || empty($test)) {
                            $cache = [];
                        }
                    }
                    if (empty($cache)) {
                        $params['rank']    = $params['column_second_id'] == 3 ? 3 : 1;
                        /**
                         * @link http://www.dataoke.com/pmc/api-d.html?id=6
                         * @see Taoke::getrankinglist
                         */
                        $data = $this->taoke->getrankinglist($params);
                        if (!empty($data['data'])) {
                            $this->redis->set($key, json_encode($data['data']), 1800);
                            $data['data'] = array_slice($data['data'], $page, $size);
                        }
                    } else {
                        $cache        = json_decode($cache, true);
                        $data['data'] = array_slice($cache, $page, $size);
                    }

                    $total = count($data['data']);
                    $res   = [
                        'data'      => $data['data'],
                        'total'     => $total,
                        'next_page' => null
                    ];
                }
                if ($params['column_second_id'] == 5) {//淘宝猜你喜欢
                    /**
                     * @link https://www.haodanku.com/api/detail/show/1.html
                     * @see Haodanku::video
                     */
                    $data = $this->taobao->optimus_material($params);
                    $res  = [
                        'data'      => $data['data'],
                        'total'     => 10000,
                        'next_page' => $data['page']
                    ];
                }
                if ($params['column_second_id'] == 6) {//京东猜你喜欢
                    $data = $this->jd->guess_like($this->params);
                    $res  = [
                        'data'      => $data['data'],
                        'total'     => 10000,
                        'next_page' => $params['page']+1,
                    ];
                }
                break;
            default:
//                $res = [];
        }
        if (!empty($res['data'])) {
            $res['data'] = $this->money_less($res['data']);
        }
        return $res;
    }


    //防止html 转义
    private function return_json($data = null, $code = 1, $msg = '操作成功', $total = 0, $next_page = null)
    {
        header('Content-Type:text/json;charset=utf-8');
        $return_data['code']      = $code;
        $return_data['data']      = $data;
        $return_data['msg']       = $msg;
        $return_data['total']     = $total;
        $return_data['next_page'] = $next_page;

        echo json_encode($return_data);
        exit();
    }
}
